<?php
/**
	小说模型
**/
namespace app\admin\controller;
use app\common\controller\Admin;
use think\Db;
use think\File;
use think\Request;
class Thirdnovel extends Admin {

	public function _initialize() {
		parent::_initialize();
		$this->getContentMenu();
		$this->model_id = $model_id = $this->request->param('model_id');
		$this->model_id = $model_id = 96;
		$list            = Db::connect("database.db_config_two")->name('Model')->where('id',$model_id)->column('*', 'id');

		if (empty($list[$model_id])) {
			return $this->error("无此模型！");
		} else {
			$this->modelInfo = $list[$model_id];
			$this->model =  Db::connect("database.db_config_two")->name("third_novel");
		}

		$this->assign('model_id', $model_id);
		$this->assign('model_list', $list);
	}

	/**
	 * 内容列表
	 * @return [html] [页面内容]
	 * @author netlife <40150501@qq.com>
	 */
	public function index() {
		if ($this->modelInfo['list_grid'] == '') {
			return $this->error("列表定义不正确！", url('admin/model/edit', array('id' => $this->modelInfo['id'])));
		}

		$allvisit = input('allvisit');
		$is_new = input('is_new');
		$is_free = input('is_free');
		$is_old = input('is_old');
		$is_license = input('is_license');
		$is_recommend = input('is_recommend');
		$index = input('index');
		$update = input('update');
		$chapters = input('chapters');
        $siteid = input('siteid');
		
		$order = '';

		if($is_new){
			$order .="create_time DESC,";
		}elseif($is_license){
			$order .="top DESC,";
		}

		$order .="allvisit asc,id desc";
		
		/*
		if($is_new && $allvisit =='asc'){
			$order = "create_time DESC,`index` DESC,allvisit asc,id desc";
		}elseif($is_new && $allvisit =='desc'){
			$order = "create_time DESC,`index` DESC,allvisit desc,id desc";
		}elseif(empty($is_new)&&$allvisit =='asc'){
			$order = "`index` DESC,id desc";
		}elseif($is_new&&empty($allvisit)){
			$order = "create_time DESC,`index` DESC,id desc";
		}else{
			$order = "`top` DESC,`index` DESC,allvisit asc,id desc";
		}*/
		

		
		$grid_list = get_grid_list($this->modelInfo['list_grid']);
		//$order     = "id desc";
		$map       = $this->buildMap();
		$field     = array_filter($grid_list['fields']);

		if($is_free){
			$articleid =  Db::connect("database.db_config_two")->name('limitedfree')->where('enddate >'.time())->order('create_time DESC')->limit(1)->value('articleid');
			$map['id'] = ['in',$articleid];
		}

		if($is_new){
			$map['create_time'] = array("<","now() + interval 7 day");
		}
		/**
		if($is_license){
			$map['articletype'] = 1;
		}*/
		
		if($index==1){
			$map['index'] = array(array(">=",91),array("<",100));
		}elseif($index==2){
			$map['index'] = array(array(">=",76),array("<=",90));
		}elseif($index==3){
			$map['index'] = array(array(">=",61),array("<=",75));
		}elseif($index==4){
			$map['index'] = array(array(">=",51),array("<=",60));
		}elseif($index==5){
			$map['index'] = array(array(">=",1),array("<=",50));
		}elseif($index==6){
			$map['index'] = 0;
		}

		//上架时间
		if($update==1){
			$starttime = mktime(0,0,0,date('m'),date('d'),date('Y'));
			$endtime = mktime(23,59,59,date('m'),date('d'),date('Y'));
			$map['create_time'] = [[">=",$starttime],["<=",$endtime]];
		}elseif($update==2){
			$starttime = mktime(0,0,0,date('m'),date('d')-7,date('Y'));
			$endtime = mktime(23,59,59,date('m'),date('d'),date('Y'));
			$map['create_time'] = [[">=",$starttime],["<=",$endtime]];
		}elseif($update==3){
			$starttime = mktime(0,0,0,date('m'),1,date('Y'));
			$endtime = mktime(23,59,59,date('m'),date('t'),date('Y'));
			$map['create_time'] = [[">=",$starttime],["<=",$endtime]];
		}

		//小说章节
		if($chapters==1){
			$map['chapters'] = array(array(">=",0),array("<",100));
		}elseif($chapters==2){
			$map['chapters'] = array(array(">=",100),array("<",300));
		}elseif($chapters==3){
			$map['chapters'] = array(array(">=",300),array("<",600));
		}elseif($chapters==4){
			$map['chapters'] = array(">=",600);
		}
		
		if($is_recommend){
			$map['']=['exp','FIND_IN_SET(9,is_top)'];
		}

		if($is_old){
			$map['']=['exp','FIND_IN_SET(10,is_top)'];
		}

        if($siteid){
            $map['siteid']=array("=",$siteid);
        }

		if(session('user_auth.group')!=999){
			$map['status'] = 1;
		}
		
		$list = $this->model->where($map)->order($order)->paginate($this->modelInfo['list_row'],false,['query' => ['is_new'=>input('is_new'),'page'=>input('page'),'siteid'=>input('siteid'),'status'=>input('status'),'channel'=>input('channel'),'category_id'=>input('category_id'),'fullflag'=>input('fullflag'),'allvisit'=>$allvisit]]);
		$catemap = [];
		$catemap['model_id'] = 1;
		if(input('channel')==1){
			$catemap['name'] = "男频";	
		}
		if(input('channel')==2){
			$catemap['name'] = "女频";	
		}
		

		$category =  Db::connect("database.db_config_two")->name('category')->where($catemap)->select();
		
		//获取授权用户组
		$access = config('cartoon_access');
		//获取当前用户组
		$group = session('user_auth.group');
		
		$novel =  Db::connect("database.db_config_two")->name('novel')->where('status = 1')->field('id,title as name')->select();
		//获取默认章节售价配置信息
		$saleprice =  Db::connect("database.db_config_two")->name('config')->where(array('name'=>'chaptersaleprice'))->field("extra")->cache(true)->find();
		$chaptersaleprice = parse_field_attr($saleprice["extra"]);
		//获取默认千字售价配置信息
		$wordsperegold =  Db::connect("database.db_config_two")->name('config')->where(array('name'=>'wordsperegold'))->field("extra")->cache(true)->find();
		$wordsperegold = parse_field_attr($wordsperegold["extra"]);
		
		$data = array(
			'grid' => $grid_list,
			'list' => $list,
			'novel' => $novel,
			'page' => $list->render(),
			'group' => $group,
			'is_new' => input('is_new'),
			'is_old' => input('is_old'),
			'is_free' => input('is_free'),
			'is_license' => input('is_license'),
			'is_recommend' => input('is_recommend'),
			'index' => $index,
			'update' => $update,
			'chapters' => $chapters,
			'status' => input('status'),
			'channel' => input('channel'),
			'fullflag'=> input('fullflag'),
			'category'=> $category,
			'category_id'=>input('category_id'),
			'access'  => $access,
			'chaptersaleprice'  => $chaptersaleprice,
			'wordsperegold'  => $wordsperegold,
			'allvisit'       => $allvisit,
			'cp_member' => $this->getCpsCpMembers(-1),
			'siteid'    => $siteid
		);
		if ($this->modelInfo['template_list']) {
			$template = 'content/' . $this->modelInfo['template_list'];
		}
		$this->assign($data);
		$this->setMeta($this->modelInfo['title'] . "列表");
		return $this->fetch($template);
	}
/**
	 * 查小说来源
	 */
	public function getCpsCpMembers($id = 0)
	{
		$res = Db::connect("database.db_config_two")->name('cp_member')->select();
		if($id>-1){
			foreach ($res as $k => $v) {
				if($v['uid'] == $id){
					return $v['nickname'];
				}
			}
			return $id ==0 ? '本站': '未知';
		}
		return $res;
		# code...
	}
	
	/*****本周推荐*****/
	public function recommend() {
	    
		if ($this->modelInfo['list_grid'] == '') {
			return $this->error("列表定义不正确！", url('admin/model/edit', array('id' => $this->modelInfo['id'])));
		}

		$order = "`index` DESC";
		
		$grid_list = get_grid_list($this->modelInfo['list_grid']);
		//$order     = "id desc";
		$map       = $this->buildMap();
		$field     = array_filter($grid_list['fields']);

		$map['']=['exp','FIND_IN_SET(9,is_top)'];

		$list = $this->model->where($map)->order($order)->paginate($this->modelInfo['list_row']);
			
		$category =  Db::connect("database.db_config_two")->name('category')->where('model_id=1')->select();

		
		$data = array(
			'grid' => $grid_list,
			'list' => $list,
			'page' => $list->render(),
			'category'=> $category
		);
	
		$this->assign($data);
		$this->setMeta("本周推荐");
		return $this->fetch();
	}


	/*****派单榜单*****/
	public function hot() {
		if ($this->modelInfo['list_grid'] == '') {
			return $this->error("列表定义不正确！", url('admin/model/edit', array('id' => $this->modelInfo['id'])));
		}

		$order = "`index` DESC";
		
		$grid_list = get_grid_list($this->modelInfo['list_grid']);
		//$order     = "id desc";
		$map       = $this->buildMap();
		$field     = array_filter($grid_list['fields']);

		$map['']=['exp','FIND_IN_SET(10,is_top)'];

		$list = $this->model->where($map)->order($order)->paginate($this->modelInfo['list_row']);
		
		$category =  Db::connect("database.db_config_two")->name('category')->where('model_id=1')->select();

		
		$data = array(
			'grid' => $grid_list,
			'list' => $list,
			'page' => $list->render(),
			'category'=> $category
		);
		
		$this->assign($data);
		$this->setMeta("本周推荐");
		return $this->fetch();
	}

	/**
	 * 内容添加
	 * @author netlife <40150501@qq.com>
	 */
	public function add() {
		if (IS_POST) {
			$this->param['uid'] = session('user_auth.uid');
			$result = $this->model->save($this->param);
			if ($result) {
				//记录行为
				action_log('add_content', 'content', $result, session('user_auth.uid'));
				return $this->success("添加成功！", url('admin/novel/index', array('model_id' => $this->modelInfo['id'])));
			} else {
				return $this->error($this->model->getError(), url('admin/novel/add', array('model_id' => $this->modelInfo['id'])));
			}
		} else {
			$info = array(
				'model_id' => $this->modelInfo['id'],
			);
			$data = array(
				'info'       => $info,
				'fieldGroup' => $this->getField($this->modelInfo),
			);
			
			if ($this->modelInfo['template_add']) {
				$template = 'content/' . $this->modelInfo['template_add'];
			} else {
				$template = 'novel/edit';
			}
			$this->assign($data);
			$this->setMeta("添加" . $this->modelInfo['title']);
			return $this->fetch($template);
		}
	}


    /**
      * uploadbook [上传小说]
      *
      * @return type
    **/
	public function uploadbook() {

		if (IS_POST) {
			$ebook = input('post.ebook');
			
			if(empty($ebook)){
				return $this->error("电子书不能为空");
			}

			if(empty($this->param["category_id"])){
				return $this->error("小说分类不能为空");
			}

			if(empty($this->param["title"])){
				return $this->error("小说名字不能为空");
			}
			
			//小说存在
			$articleinfo =  Db::connect("database.db_config_two")->name('novel')->where('title','like','%'.$this->param["title"].'%')->value('id');

			if($articleinfo){
				$articleid =$articleinfo;
				$chapters =  Db::connect("database.db_config_two")->name('novel')->where('title','like','%'.$this->param["title"].'%')->value('chapters');
			}else{//不存在
				$this->param['create_time'] = time();
				$this->param['update_time'] = time();
				$result = $this->model->save($this->param);
				$articleid = $this->model->getLastInsID();
				$chapters =0;
			}
			
			//增加章节
			if($articleid){
				$info =  Db::connect("database.db_config_two")->name('novel')->where("id",$articleid)->find();

				$bookList = $this->readList($ebook);

				$i = $chapters?$chapters:1;
				foreach($bookList as $k=>$v){
					$chapterdata['articleid'] = $articleid;
					$chapterdata['uid'] = session("user_auth.uid");
					$chapterdata['chaptername'] = $v["name"];
					//$chapterdata['content'] = $v["content"];
					$chapterdata['create_time'] = time();
					$chapterdata['update_time'] = time();
					$chapterdata['size'] = get_count_content($v['content']);
					$chapterdata['saleprice'] = round($chapterdata['size']/1000*config('wordsperegold'));
					if($i>20){
						$chapterdata['isvip'] = 1;
						$chapterdata['saleprice'] = round($chapterdata['size']/1000*config('wordsperegold'));
					}
					
					$chapterdata['chapterorder'] = $i;
					$chapterdata['articlename'] = $this->param['title'];
					 Db::connect("database.db_config_two")->name('chapter')->insert($chapterdata);

					$chapterId =  Db::connect("database.db_config_two")->name('chapter')->getLastInsID();
					
					//更新小说章节内容
					$ocontent['chapterid'] = $chapterId;
					//$ocontent['content'] = "<p>".str_replace(array("\r\n", "\r", "\n"),'</p><p>',$v["content"])."</p>";
					$ocontent['content'] = $this->format_content($v["content"]);
					//数据分表开启的时候
					if(config('partition')){
						$rule = [
							'type' => 'mod', // 分表方式
							'num'  => 10     // 分表数量
						];
						 Db::connect("database.db_config_two")->name("novel_content")->partition(['chapterid' => $chapterId], "chapterid", $rule)->insert($ocontent);
					}else{
						 Db::connect("database.db_config_two")->name("novel_content")->insert($ocontent);
					}

					//更新小说章节最新信息
					 Db::connect("database.db_config_two")->name('novel')->where(array('id'=>$articleid))->update(array('lastvolumeid'=>$chapterId,'lastvolume'=>$v["name"]));
					
					$size += $chapterdata['size'];
					$i++;
				}
				//更新小说总字数
				$addorup = visit_addorup($info['update_time']);
				$monthsize = $addorup['month']?$size:($info['monthsize']+$size);
				if (1 < $addorup['month']) {
					$premonthsize = 0;
					$premonthupds = 0;
					$monthupds = 0;
				}
				else if ($addorup['month'] == 1) {
					$premonthsize = $info['monthsize'];
					$premonthupds = $info['monthupds'];
					$monthupds = 0;
				}

				if ($addorup['day']) {
					$monthupds = $info['monthupds']+1;
				}

				 Db::connect("database.db_config_two")->name('novel')->where(array('id'=>$articleid))->update(array('chapters'=>$i,'update_time'=>time(),'size'=>array('exp', '`size`+'.$size),'monthsize'=>$monthsize,'premonthsize'=>$premonthsize,'monthupds'=>$monthupds,'premonthupds'=>$premonthupds));
				
			}
			
			//记录行为
			action_log('add_content', 'content', $result, session('user_auth.uid'));
			return $this->success("添加成功！", url('admin/novel/index', array('model_id' => $this->modelInfo['id'])));
			/**	
			} else {
				return $this->error($this->model->getError(), url('admin/novel/add', array('model_id' => $this->modelInfo['id'])));
			}
			***/
		} else {
			$info = array(
				'model_id' => $this->modelInfo['id'],
			);
			$data = array(
				'info'       => $info,
				'fieldGroup' => $this->getField($this->modelInfo),
			);
			
			$this->assign($data);
			$this->setMeta("上传小说");
			return $this->fetch();
		}
	}

    function read_txt($fileName)

    {

        $contents = file_get_contents($fileName);

//获取文件的编码方式

        $encoding = mb_detect_encoding($contents, array('GB2312', 'GBK', 'UTF-16', 'UCS-2', 'UTF-8', 'BIG5', 'ASCII'));

        $fp = fopen($fileName, "r");//以只读的方式打开文件

        $text = "

";
        $num = 0;

        if (!(feof($fp))) {

            $num++;

            $str = trim(fgets($fp));

            if ($encoding != false) {

//iconv ()将$encoding 转换成“UTF-8”

                $str = iconv($encoding, 'UTF-8', $str);

                if ($str != "" and $str != NULL) {

                    $text = $str;

                }

            } else {

                $str = mb_convert_encoding($str, 'UTF-8', 'Unicode');

                if ($str != "" and $str != NULL) {

                    $text = $str;

                }

            }

        }

        while (!(feof($fp))) {

            $str = '';

            $str = trim(fgets($fp));

            if ($encoding != false) {

                $str = iconv($encoding, 'UTF-8', $str);

                if ($str != "" and $str != NULL) {

                    $text = $text . "
" . $str;

                }

            } else {

                $str = mb_convert_encoding($str, 'UTF-8', 'Unicode');

                if ($str != "" and $str != NULL) {

                    $text = $text . "
" . $str;

                }

            }

        }

        $text .= '

';
        return $text;

    }


    /**
      * chapterupdate [章节批量更新]
      *
      * @return type
    **/
	public function chapterupdate() {

		if (IS_POST) {
            $file = request()->file('book');

            $info = $file->validate(['size'=>52428800,'ext'=>'txt'])->move( 'uploads/updatebooktxt/');  //->move('upload' . '/' . 'banana');
            if($info){
                $site =  "uploads/updatebooktxt/".$info->getSaveName();
                $site = str_replace("\\","/",$site);
            }else{
                return $this->error("请上传小于10M的TXT档");
            }
//			$ebook = input('post.ebook');
            $ebook = $site;
			$articleid = $bookid = input('post.bookid');

			if(empty($bookid)){
				return $this->error("小说不存在");
			}
			
			if(empty($ebook)){
				return $this->error("电子书不能为空");
			}
			
			//增加章节
			if($bookid){
				$info =  Db::connect("database.db_config_two")->name('novel')->where("id",$bookid)->find();

				$chapterlist =  Db::connect("database.db_config_two")->name('chapter')->where('articleid='.$bookid)->where("status",1)->order('chapterorder ASC')->column('id');
				
				$bookList = $this->readList($ebook);

				//上传的章节大于目前章节
				if(count($bookList)>=count($chapterlist)){
					$i=1;
					$size = 0;
					foreach($bookList as $k=>$v){
						if($chapterlist[$k]){
							$chapterdata['chaptername'] = $v["name"];
							$chapterdata['update_time'] = time();
							$chapterdata['size'] = get_count_content($v['content']);
							if($i>20){
								$chapterdata['isvip'] = 1;
								$chapterdata['saleprice'] = round($chapterdata['size']/1000*config('wordsperegold'));
							}
							$chapterdata['chapterorder'] = $i;
							 Db::connect("database.db_config_two")->name('chapter')->where('id', $chapterlist[$k])->update($chapterdata);
							$lastvolumeid = $chapterlist[$k];

							//更新小说章节内容
							$ocontent['content'] = "<p>".str_replace(array("\r\n", "\r", "\n"),'</p><p>',$v["content"])."</p>";
							
							//数据分表开启的时候
							if(config('partition')){
								$rule = [
									'type' => 'mod', // 分表方式
									'num'  => 10     // 分表数量
								];
								 Db::connect("database.db_config_two")->name("novel_content")->partition(['chapterid' =>$chapterlist[$k]], "chapterid", $rule)->where('chapterid', $chapterlist[$k])->update($ocontent);
							}else{
								 Db::connect("database.db_config_two")->name("novel_content")->where('chapterid',$lastvolumeid)->update($ocontent);
							}
							//记录行为
							action_log('update_chapter', 'chapter', $lastvolumeid,session('user_auth.uid'));
							
						}else{//章节不存在的情况下
							$chapterdata['articleid'] = $articleid;
							$chapterdata['uid'] = session("user_auth.uid");
							$chapterdata['chaptername'] = $v["name"];
							$chapterdata['create_time'] = time();
							$chapterdata['update_time'] = time();
							$chapterdata['size'] = get_count_content($v['content']);;
							if($i>20){
								$chapterdata['isvip'] = 1;
								$chapterdata['saleprice'] = round($chapterdata['size']/1000*config('wordsperegold'));
							}
							
							$chapterdata['chapterorder'] = $i;
							$chapterdata['articlename'] =get_novel($bookid,'title');
							 Db::connect("database.db_config_two")->name('chapter')->insert($chapterdata);

							$lastvolumeid = $chapterId =  Db::connect("database.db_config_two")->name('chapter')->getLastInsID();
							
							//更新小说章节内容
							$ocontent['chapterid'] = $chapterId;
							$ocontent['content'] = "<p>".str_replace(array("\r\n", "\r", "\n"),'</p><p>',$v["content"])."</p>";

							//数据分表开启的时候
							if(config('partition')){
								$rule = [
									'type' => 'mod', // 分表方式
									'num'  => 10     // 分表数量
								];
								 Db::connect("database.db_config_two")->name("novel_content")->partition(['chapterid' => $chapterId], "chapterid", $rule)->insert($ocontent);
							}else{
								 Db::connect("database.db_config_two")->name("novel_content")->insert($ocontent);
							}

							//记录行为
							action_log('add_chapter', 'chapter', $lastvolumeid,session('user_auth.uid'));
						}
						//更新小说章节最新信息
						 Db::connect("database.db_config_two")->name('novel')->where(array('id'=>$bookid))->update(array('lastvolumeid'=>$lastvolumeid,'lastvolume'=>$v["name"]));
						$size += $chapterdata['size'];
						$i++;
					}

					//更新小说总字数
					$addorup = visit_addorup($info['update_time']);
					$monthsize = $addorup['month']?$size:($info['monthsize']+$size);
					if (1 < $addorup['month']) {
						$premonthsize = 0;
						$premonthupds = 0;
						$monthupds = 0;
					}
					else if ($addorup['month'] == 1) {
						$premonthsize = $info['monthsize'];
						$premonthupds = $info['monthupds'];
						$monthupds = 0;
					}

					if ($addorup['day']) {
						$monthupds = $info['monthupds']+1;
					}

					 Db::connect("database.db_config_two")->name('novel')->where(array('id'=>$bookid))->update(array('chapters'=>$i,'update_time'=>time(),'size'=>$size,'monthsize'=>$monthsize,'premonthsize'=>$premonthsize,'monthupds'=>$monthupds,'premonthupds'=>$premonthupds));
				}else{
					$i=0;
					$chapterorder = 1;
					$size = 0;
					$notchapter = array();
					
					foreach($chapterlist as $k=>$v){
						if($v&&$bookList[$i]){
							$chapterid= $v;
							$chapterdata['chaptername'] = $bookList[$i]["name"];
							$chapterdata['update_time'] = time();
							$chapterdata['size'] = get_count_content($bookList[$i]['content']);
							if($i>20){
								$chapterdata['isvip'] = 1;
								$chapterdata['saleprice'] = round($chapterdata['size']/1000*config('wordsperegold'));
							}
							$chapterdata['chapterorder'] = $chapterorder;
							
							 Db::connect("database.db_config_two")->name('chapter')->where('id', $chapterid)->update($chapterdata);
							$lastvolumeid = $chapterid;

							//更新小说章节内容
							$ocontent['content'] = "<p>".str_replace(array("\r\n", "\r", "\n"),'</p><p>',$bookList[$i]["content"])."</p>";
							//数据分表开启的时候
							if(config('partition')){
								$rule = [
									'type' => 'mod', // 分表方式
									'num'  => 10     // 分表数量
								];
								 Db::connect("database.db_config_two")->name("novel_content")->partition(['chapterid' => $chapterid], "chapterid", $rule)->where('chapterid',$chapterid)->update($ocontent);
							}else{
								 Db::connect("database.db_config_two")->name("novel_content")->where('chapterid',$chapterid)->update($ocontent);
							}
							//记录行为
							action_log('update_chapter', 'chapter', $chapterid,session('user_auth.uid'));

							//更新小说章节最新信息
							 Db::connect("database.db_config_two")->name('novel')->where(array('id'=>$bookid))->update(array('lastvolumeid'=>$lastvolumeid,'lastvolume'=>$bookList[$i]["name"]));
							$size += $chapterdata['size'];

							$i++;
						}else{//章节不存在的情况下
							$notchapter[]=$v;
						}
						$chapterorder++;
					}
					//更新小说总字数
					$addorup = visit_addorup($info['update_time']);
					$monthsize = $addorup['month']?$size:($info['monthsize']+$size);
					if (1 < $addorup['month']) {
						$premonthsize = 0;
						$premonthupds = 0;
						$monthupds = 0;
					}
					else if ($addorup['month'] == 1) {
						$premonthsize = $info['monthsize'];
						$premonthupds = $info['monthupds'];
						$monthupds = 0;
					}

					if ($addorup['day']) {
						$monthupds = $info['monthupds']+1;
					}

					 Db::connect("database.db_config_two")->name('novel')->where(array('id'=>$bookid))->update(array('chapter'=>$i,'update_time'=>time(),'size'=>$size,'monthsize'=>$monthsize,'premonthsize'=>$premonthsize,'monthupds'=>$monthupds,'premonthupds'=>$premonthupds));
					//删除不存在的章节
					if($notchapter){
						//删除章节
						 Db::connect("database.db_config_two")->name('chapter')->where(['id'=>array('IN',$notchapter)])->delete();	
						//删除章节内容
						 Db::connect("database.db_config_two")->name('novel_content')->where(['chapterid'=>array('IN',$notchapter)])->delete();
						//记录行为
						action_log('delete_chapter', 'chapter', '', session('user_auth.uid'));
					}
				}
			}
			return $this->success("更新成功！", url('admin/novel/index'));
		} else {
			$this->assign('bookid',input('id'));
			$this->setMeta("章节批量更新");
			return $this->fetch();
		}
		
	}

	public function updatelist() {
		$type = input('type')?input('type'):"monthupds";
		$order = "";

		if($type){
			$order = $type." desc";
		}
		$list  =  Db::connect("database.db_config_two")->name('novel')->order($order)->paginate($this->modelInfo['list_row'],false,['query' => ['type'=>$type]]);

		$data = [
			'list'=>$list,
			'page' => $list->render(),
			'type'=>$type,
		];
		$this->assign($data);
		$this->setMeta("更新排行榜");
		return $this->fetch();
	}

	public function setfocuschapter() {
		$bookid = input('bookid');
		$volumeorder = input('volumeorder');
		$uid = session('user_auth.uid');
		
		//是否存在此本书的关注信息
		$focuschapter =  Db::connect("database.db_config_two")->name('chapter_focus')->where(array('uid'=>$uid,'articleid'=>$bookid))->find();
		if($focuschapter){
			$result    = Db::connect("database.db_config_two")->name('chapter_focus')->where(array('uid'=>$uid,'articleid'=>$bookid))->setField('focuschapter', $volumeorder);
		}else{
			$data = array(
				"uid"=>$uid,
				"create_time"=>time(),
				"update_time"=>time(),
				"articleid"=>$bookid,
				"focuschapter"=>$volumeorder
			);
			$result= Db::connect("database.db_config_two")->name('chapter_focus')->insert($data);
		}
		
		if (false !== $result) {
			//批量设置推广链接关注章节
			$tuiguang =  Db::connect("database.db_config_two")->name('tuiguang')->where(array('uid'=>$uid,'articleid'=>$bookid))->column('id');
			if($tuiguang){
				foreach ($tuiguang as $k=>$v){
					 Db::connect("database.db_config_two")->name('tuiguang')->where('id='.$v)->setField('followchapter', $volumeorder);
				}
			}
			return $this->success("操作成功！");
		} else {
			return $this->error("操作失败！！");
		}
	}

	public function copy() {
		header('Content-Type: text/event-stream'); // 以事件流的形式告知浏览器进行显示
		header('Cache-Control: no-cache');         // 告知浏览器不进行缓存
		header('X-Accel-Buffering: no');           // 关闭加速缓冲
		$this->setMeta("复制小说");
		$this->assign("bookid",input('id'));
		return $this->fetch();
	}

	public function copyaction() {
		ini_set('memory_limit','512M');
		set_time_limit(0);
		$bookid = input('id');
		
		//获取小说信息
		$info =  Db::connect("database.db_config_two")->name('novel')->where('id',$bookid)->find();
		echo str_repeat(" ",1024*64);
		echo "《".$info["title"]."》开始复制小说详情\r\n<br>";
		ob_flush();
		flush();
		unset($info['id']);
		unset($info['allvisit']);
		unset($info['allcollect']);
		unset($info['goodnum']);
		$info['title'] = $info['title']."-副本";
		$articleid =  Db::connect("database.db_config_two")->name("novel")->insertGetId($info);
		if($articleid){
			echo str_repeat(" ",1024*64);
			echo "《".$info["title"]."》小说信息复制完成\r\n<br>";
			ob_flush();
			flush();
			$chapters =  Db::connect("database.db_config_two")->name('chapter')->where('articleid',$bookid)->order('chapterorder ASC')->select();
			if($chapters){
				$i = 1;
				$lastchapter = '';
				$lastchapterid = 0;
				$size = 0;
				$chapterorder = 0;
				foreach ($chapters as $kk=>$vv){
					$lastchapter = $vv["chaptername"];
					$lastchapterid = $vv["id"];
					$size +=$vv["size"];
					$chapterorder = $kk+1;
					$chapter['articleid'] = $articleid;
					$chapter['articlename'] = $info['title'];
					$chapter['uid'] = session('user_auth.uid');
					$chapter['chaptername'] = $vv["chaptername"];
					$chapter['size'] = $vv["size"];
					$chapter['isvip'] = $vv["isvip"];
					if(config('pricetype')==1){
						$chapter['saleprice'] = config('chaptersaleprice');
					}else{
						$chapter['saleprice'] = round($vv["size"]/1000*config('wordsperegold'));
					}
					$chapter['create_time'] =$vv["create_time"];
					$chapter['update_time'] =$vv["update_time"];
					$chapter['chapterorder'] = $chapterorder;
					$chapterid =  Db::connect("database.db_config_two")->name("chapter")->insertGetId($chapter);
					
					$content =  Db::connect("database.db_config_two")->name('novel_content')->where("chapterid",$vv['id'])->find();
					$ocontent['chapterid'] = $chapterid;
					$ocontent['content'] = $content['content'];
					 Db::connect("database.db_config_two")->name("novel_content")->insert($ocontent);
					echo str_repeat(" ",1024*64);
					echo "《".$info["title"]."》--".$vv["chaptername"]."章节复制完成\r\n<br>";
					ob_flush();
					flush();
				}
				//更新最新信息至小说表
				 Db::connect("database.db_config_two")->name("novel")->where('id',$articleid)->update(['lastvolume' =>$lastchapter,'lastvolumeid' =>$lastchapterid,'chapters' =>$chapterorder,'size' =>$size,'update_time'=>time()]);

			}
		}
		ob_end_flush();//输出并关闭缓冲
		die;
	}

	public function sync() {
		header('Content-Type: text/event-stream'); // 以事件流的形式告知浏览器进行显示
		header('Cache-Control: no-cache');         // 告知浏览器不进行缓存
		header('X-Accel-Buffering: no');           // 关闭加速缓冲
		$this->setMeta("同步小说");
		return $this->fetch();
	}

	/*****同步小说数据****/
	public function newsync() {
		$pageli = input('key')>0?input('key'):1;
		$category = [
			1=>['id'=>6,'channel'=>1],
			2=>['id'=>7,'channel'=>1],
			3=>['id'=>8,'channel'=>1],
			4=>['id'=>9,'channel'=>1],
			5=>['id'=>10,'channel'=>1],
			6=>['id'=>14,'channel'=>1],
			7=>['id'=>15,'channel'=>1],
			8=>['id'=>1,'channel'=>2],
			9=>['id'=>2,'channel'=>2],
			10=>['id'=>3,'channel'=>2],
			11=>['id'=>4,'channel'=>2],
			12=>['id'=>5,'channel'=>2],
			13=>['id'=>11,'channel'=>2],

		];
		$listurl = "http://fanqie.bowenyd.com/apis/share/get_book_list.php?ssid=9";
		$list = $this->curl_get($listurl);
		header("Content-Encoding: none\r\n");
		ob_start();//打开缓冲区
		echo str_repeat(" ",1024*64);
		echo "本次总共需要同步".count($list["data"])."个,第".$pageli."个正在同步，请稍等...\r\n<br>";
		
		if($pageli<=count($list["data"])){
			$v = $list["data"][$pageli-1];
			//获取小说详情URL
			$infourl = "http://fanqie.bowenyd.com/apis/share/get_book_info.php?ssid=9&aid={bookid}";
			$infourl = str_replace("{bookid}",$v["articleid"],$infourl);
			
			//获取小说详情
			$info= $this->curl_get($infourl);
			$info = $info["data"];
			//小说存在
			$articleinfo =  Db::connect("database.db_config_two")->name('novel')->where('title','like','%'.$info["articlename"].'%')->value('id');
			echo str_repeat(" ",1024*64);
			echo "《".$info["articlename"]."》开始同步\r\n<br>";
			ob_flush();
			flush();
			if($articleinfo){
				$articleid =$articleinfo;
			}else{//不存在
				$data['create_time'] = strtotime($info['postdate']);
				$data['update_time'] = strtotime($info['lastupdate']);	
				$data['title'] = $info['articlename'];
				$data['keywords'] = $info['keywords'];
				$data['author'] = $info['author'];
				$data['intro'] = $info['intro'];
				$data['fullflag'] = $info['fullflag'];
				$data['articletype'] = 1;
				if($info['sortid']){
					$data['channel'] = $category[$info['sortid']]['channel'];
					$data['category_id'] = $category[$info['sortid']]['id'];	
				}else{
					$data['channel'] = 0;
					$data['category_id'] = 0;	
				}
				$save_dir =  "uploads/novelhumb/".date('Ymd')."/";
				if($info["cover"]){
					$data['cover'] = file_get_img($info["cover"],$save_dir,1);
				}
				$articleid =  Db::connect("database.db_config_two")->name("novel")->insertGetId($data);
			}
			//获取小说章节URL
			$volumeurl = "http://fanqie.bowenyd.com/apis/share/get_chapter_list.php?ssid=9&aid={bookid}";
			$volumeurl = str_replace("{bookid}",$v["articleid"],$volumeurl);
			//获取小说详情
			$volume= $this->curl_get($volumeurl);
			$volume= $volume["data"];
			if($volume){	
				$chapters =  Db::connect("database.db_config_two")->name('novel')->where('id',$articleid)->value('chapters');
				$i = 1;
				foreach($volume as $kk=>$vv){
					//判断是否有最新需要同步的章节
					if($vv['chapterorder'] >$chapters){			
						//更新章节
						$chapter['articleid'] = $articleid;
						$chapter['articlename'] = $info['articlename'];
						$chapter['uid'] = session('user_auth.uid');
						$chapter['chaptername'] = $vv["chaptername"];
						$chapter['size'] = $vv["words"];
						$chapter['isvip'] = $vv["isvip"];
						$chapter['saleprice'] = $vv["saleprice"];
						$chapter['create_time'] = strtotime($vv["postdate"])?strtotime($vv["postdate"]):time();
						$chapter['update_time'] = strtotime($vv["lastupdate"])?strtotime($vv["lastupdate"]):time();
						$chapter['chapterorder'] = $chapters+$i;
						$chapterid =  Db::connect("database.db_config_two")->name("chapter")->insertGetId($chapter);
						if($chapterid){
							//更新最新信息至小说表
							 Db::connect("database.db_config_two")->name("novel")->where('id',$articleid)->update(['lastvolume' => $vv["chaptername"],'lastvolumeid' => $chapterid,'chapters' =>['exp','chapters+1'],'size' =>['exp','size+'.$vv["words"]],'update_time'=>time()]);
						}
						
						//获取小说内容URL
						$contenturl = "http://fanqie.bowenyd.com/apis/share/get_chapter_content.php?ssid=9&aid={bookid}&cid={chapterid}";
						$contenturl = str_replace(array("{bookid}","{chapterid}"),array($v["articleid"],$vv["chapterid"]),$contenturl);
						//获取小说内容
						$content= $this->curl_get($contenturl);
						$content= $content["data"];
						$ocontent['chapterid'] = $chapterid;
						$ocontent['content'] = "<p>".str_replace(array("\r\n", "\r", "\n"),'</p><p>',$content["content"])."</p>";
						
						 Db::connect("database.db_config_two")->name("novel_content")->insert($ocontent);
						$i++;
						echo str_repeat(" ",1024*64);
						echo "《".$info["articlename"]."》--".$vv["chaptername"]."章节同步完成\r\n<br>";
						ob_flush();
						flush();
					}
					
				}
			}
			$pageli++;
			echo str_repeat(" ",1024*64);
			echo "《".$info["articlename"]."》同步完成\r\n<br>";
			ob_flush();
			flush();
			$jumpUrl = url('novel/newsync',array('model_id'=>1,'key'=>$pageli));
			echo "<script language=javascript>
					setTimeout('window.location=\"".$jumpUrl."\"',500)
				</script>";

		}else{
			echo str_repeat(" ",1024*64);
			echo "所有内容同步完成\r\n<br>";
			ob_flush();
			flush();
		}
		ob_end_flush();//输出并关闭缓冲
		die;
	}

	/**
	 * 内容修改
	 * @author netlife <40150501@qq.com>
	 */
	public function edit($id) {
		if (IS_POST) {
			//$result = $this->model->save($this->param, array('id'=> $id));
			$this->param["viptime"] = strtotime($this->param["viptime"]);
			$this->param["signtime"] = strtotime($this->param["signtime"]);
			$result =  Db::connect("database.db_config_two")->name('novel')->cache('bookinfo'.$id)->where('id',$id)->update($this->param);
			if ($result !== false) {
				//记录行为
				action_log('update_content', 'content', $result, session('user_auth.uid'));
				return $this->success("更新成功！", url('admin/novel/index', array('model_id' => $this->modelInfo['id'])));
			} else {
				return $this->error($this->model->getError(), url('admin/novel/edit', array('model_id' => $this->modelInfo['id'], 'id' => $id)));
			}
		} else {
			if (!$id) {
				return $this->error("非法操作！");
			}
			$info = $this->model->find($id);
			if (!$info) {
				return $this->error($this->model->getError());
			}
			$info['model_id'] = $this->modelInfo['id'];
			$data             = array(
				'info'       => $info,
				'fieldGroup' => $this->getField($this->modelInfo),
			);
			
			$this->assign($data);
			$this->setMeta("编辑" . $this->modelInfo['title']);
			return $this->fetch();
		}
	}

	/**
	 * 内容删除
	 * @author netlife <40150501@qq.com>
	 */
	public function del() {
		$id = $this->getArrayParam('id');
		if (empty($id)) {
			return $this->error("非法操作！");
		}

		$map['id'] = array('IN', $id);
		
		$result    = $this->model->where($map)->delete();

		if (false !== $result) {
			$chapterid =  Db::connect("database.db_config_two")->name('chapter')->where(['articleid'=>array('IN', $id)])->column('id');
			//删除章节
			 Db::connect("database.db_config_two")->name('chapter')->where(['articleid'=>array('IN', $id)])->delete();	
			//删除章节内容
			 Db::connect("database.db_config_two")->name('novel_content')->where(['chapterid'=>array('IN', implode(',',$chapterid))])->delete();

			//记录行为
			action_log('delete_novel', 'novel', $result, session('user_auth.uid'));
			return $this->success("删除成功！");
		} else {
			return $this->error("删除失败！");
		}
	}


	//小说删除日志
	public function dellog() {
		$keyword = input('keyword');
		
		//获取列表数据
		$map['status'] = array('gt', -1);
		$map['model'] = "chapter";

		if($keyword){
			$map['remark'] = array("LIKE", "%$keyword%");
		}


		$order = "id desc";
		//获取列表数据
		$list = 
			model('ActionLog')->where($map)->order($order)->paginate(10);

		$data = array(
			'list' => $list,
			'keyword' => $keyword,
			'page' => $list->render(),
		);
		$this->assign($data);
		$this->setMeta('小说删除日志');
		return $this->fetch();
	}

	/**
	 * 设置显示状态
	 * @author netlife <40150501@qq.com>
	 */
	public function displays($id, $status) {
		$map['id'] = $id;
		$result    = $this->model->where($map)->setField('display', $status);
		if (false !== $result) {
			return $this->success("操作成功！");
		} else {
			return $this->error("操作失败！！");
		}
	}

	/**
	 * 设置置顶状态
	 * @author netlife <40150501@qq.com>
	 */
	public function tops($id, $status) {
		$map['id'] = $id;
		$result    = $this->model->where($map)->setField('top', $status);
		if (false !== $result) {
			return $this->success("操作成功！");
		} else {
			return $this->error("操作失败！！");
		}
	}


	/**
	 * 设置状态
	 * @author netlife <40150501@qq.com>
	 */
	public function status($id, $status) {
		$map['id'] = $id;
		$result    = $this->model->where($map)->setField('status', $status);
		if (false !== $result) {
			return $this->success("操作成功！");
		} else {
			return $this->error("操作失败！！");
		}
	}

	/**
	 * 新作设置状态
	 * @author netlife <40150501@qq.com>
	 */
	public function newstatus($id, $status) {
		$map['id'] = $id;
		$result    = $this->model->where($map)->setField('status', $status);
		if (false !== $result) {
			return $this->success("操作成功！");
		} else {
			return $this->error("操作失败！！");
		}
	}
	/****全本下载*****/
	public function down() {
		$id = input('id');
		$filename =  Db::connect("database.db_config_two")->name('third_novel')->where("id=".$id)->value("title");
		$filename = $filename.".txt";
		$encoded_filename = urlencode($filename);    
		$encoded_filename = str_replace("+", "%20", $encoded_filename);  
		
		header("Content-Type: application/octet-stream");      
		if (preg_match("/MSIE/", $_SERVER['HTTP_USER_AGENT']) ) {
			header('Content-Disposition:  attachment; filename="' . $encoded_filename . '"');      
		} elseif (preg_match("/Firefox/", $_SERVER['HTTP_USER_AGENT'])) {      
			header('Content-Disposition: attachment; filename*="utf8' .  $filename . '"');      
		} else {      
			header('Content-Disposition: attachment; filename="' .  $filename . '"');      
		} 
		
		//$chapter =  Db::connect("database.db_config_two")->name('chapter')->where("articleid=".$id)->order("	chapterorder ASC")->column('id,chaptername');
        $chapter =  Db::connect("database.db_config_two")->name('third_chapter')->where("articleid=".$id)->order("	id ASC")->column('id,chaptername');
		if($chapter){
			
			foreach ($chapter as $k=>$v){
				$chaptername = "";
				$content =  Db::connect("database.db_config_two")->name('third_novel_content')->where("chapterid=".$k)->value("content");
				$content =str_replace(array("　","  ","<p></p>"),"",$content);
				if(strpos($v,"第")===false){
					preg_match_all("/\d+/is",$v,$arr);
					$chaptername = str_replace($arr[0][0],"第".$arr[0][0]."章",$v);
				}else{
					$chaptername = $v;
				}
				$content = "\r\n\r\n\t".$chaptername."\r\n\r\n\t".str_replace(array("<p>","</p>"),array("","\r\n\r\n\t"),$content);
				echo strip_tags($content);
			}
		}
	}

	/**
	 * 设置置顶
	 * @author netlife <40150501@qq.com>
	 */
	public function settop($id, $is_top) {
		/*
		$map['id'] = $id;
		$result    = $this->model->where($map)->setField('is_top', $is_top);
		if (false !== $result) {
			return $this->success("操作成功！");
		} else {
			return $this->error("操作失败！！");
		}
		*/
		$map['id'] = $id;
		$top =	$this->model->where($map)->value('is_top');
		if($top){
			$top = explode(',',$top);
			$top[] = $is_top;
			array_unique($top);
			$is_top = implode(",",$top);
		}
		$result    = $this->model->where($map)->setField('is_top', $is_top);
		if (false !== $result) {
			return $this->success("操作成功！");
		} else {
			return $this->error("操作失败！！");
		}
	}

	/****取消推荐******/
	public function unsettop($id, $is_top) {
		$map['id'] = $id;
		$top =	$this->model->where($map)->value('is_top');
		if($top){
			$top = explode(',',$top);
			foreach($top as $k=>$v){
				if($v ==$is_top){
					unset($top[$k]);
				}
			}
			$is_top = implode(",",$top);
		}
		$result    = $this->model->where($map)->setField('is_top', $is_top);
		if (false !== $result) {
			return $this->success("操作成功！");
		} else {
			return $this->error("操作失败！！");
		}
	}
	/****设置VIP******/
	public function setvip() {
		$id = input('id');
		$action = input('action');
		if (empty($id)) {
			return $this->error("非法操作！");
		}
		/*******章节列表页设置VIP章节专用********/
		if(!empty($action)){
			$post = input('');
			$isvip = $post['type']=='vip'?1:0;
			if($isvip){
				$chapter =  Db::connect("database.db_config_two")->name('chapter')->where(['articleid'=>$post['articleid']])->update(['isvip' =>0]);
			}
			$chapter =  Db::connect("database.db_config_two")->name('chapter')->where(['articleid'=>$post['articleid'],'chapterorder'=>array('>=',$post['chapterorder'])])->order('chapterorder ASC')->column('id,size');
			foreach($chapter as $k=>$v){
				if(config('pricetype')==1){//按章
					$price = config('chaptersaleprice');
					if($isvip){
						 Db::connect("database.db_config_two")->name('chapter')->where('id='.$k)->update(['chaptersaleprice'=>$price,'isvip'=>1]);
					}else{
						 Db::connect("database.db_config_two")->name('chapter')->where('id='.$k)->update(['isvip' =>$isvip]);
					}
				}else{
					$saleprice = round($v/1000*config('wordsperegold'));
					if($isvip){
						 Db::connect("database.db_config_two")->name('chapter')->where('id='.$k)->update(['isvip' =>$isvip,'saleprice'=>$saleprice]);
					}else{
						 Db::connect("database.db_config_two")->name('chapter')->where('id='.$k)->update(['isvip' =>$isvip]);
					}
				}
			}
			return $this->success("设置成功！");
		}
		/*******章节列表页设置VIP章节专用结束********/
		if(IS_POST){
			$post = input('post.');
			$isvip = $post['type']=='vip'?1:0;
			if($isvip){
				$chapter =  Db::connect("database.db_config_two")->name('chapter')->where(['articleid'=>$post['articleid']])->update(['isvip' =>0]);
			}
			$chapter =  Db::connect("database.db_config_two")->name('chapter')->where(['articleid'=>$post['articleid'],'id'=>array('>',$post['chapterid'])])->column('id,size');
			foreach($chapter as $k=>$v){
				if(config('pricetype')==1){//按章
					$price = config('chaptersaleprice');
					if($isvip){
						 Db::connect("database.db_config_two")->name('chapter')->where('id='.$k)->update(['chaptersaleprice'=>$price,'isvip'=>1]);
					}else{
						 Db::connect("database.db_config_two")->name('chapter')->where('id='.$k)->update(['isvip' =>$isvip]);
					}
				}else{
					$saleprice = round($v/1000*config('wordsperegold'));
					if($isvip){
						 Db::connect("database.db_config_two")->name('chapter')->where('id='.$k)->update(['isvip' =>$isvip,'saleprice'=>$saleprice]);
					}else{
						 Db::connect("database.db_config_two")->name('chapter')->where('id='.$k)->update(['isvip' =>$isvip]);
					}
				}
			}
			return $this->success("设置成功！", url('admin/novel/index', array('model_id' => $this->modelInfo['id'])));
		}
		$chapter =  Db::connect("database.db_config_two")->name('chapter')->where('articleid='.$id)->column('id,chaptername,isvip');
		$this->assign('id',$id);
		$this->setMeta("批量设置VIP");
		$this->assign('chapter',$chapter);
		return $this->fetch();
	}

	/*****字数统计******/
	public function setsize() {
		$id = input('id');
		if (empty($id)) {
			return $this->error("非法操作！");
		}
		
		$chapter =  Db::connect("database.db_config_two")->name('chapter')->where(['articleid'=>$id,'status'=>1])->column('id');
		$chaptersize = 0;
		foreach($chapter as $v){
			$content =  Db::connect("database.db_config_two")->name('novel_content')->where('chapterid = '.$v)->value('content');

			$content = $this->textstr($content);
			
			$size = round(strlen(preg_replace('/\\s/', '', strip_tags($content)))/3);
			
			 Db::connect("database.db_config_two")->name('chapter')->where('id='.$v)->cache('bookinfo'.$id)->update(['size' =>$size]);
			$chaptersize +=$size;
		}
		
		 Db::connect("database.db_config_two")->name('novel')->where(['id'=>$id])->update(['size' =>$chaptersize]);

		return $this->success("设置成功！", url('admin/novel/index', array('model_id' => $this->modelInfo['id'])));
		
	}
	/***设置价格*****/
	public function setprice() {
		$getid = input();
		
		if(is_array($getid['id'])){
			$id = implode(',',$getid['id']);
		}else{
			$id = $getid['id'];
		}
		
		if(IS_POST){
			$post = input('post.');

			if(empty($post['price'])){
				return $this->error("售价不能为空！");
			}
			if(strpos($post['articleid'],',')!==false){
				$chapter =  Db::connect("database.db_config_two")->name('chapter')->where(['articleid'=>['in',$post['articleid']],'isvip'=>"1"])->column('id,size');
				
			}else{
				$chapter =  Db::connect("database.db_config_two")->name('chapter')->where(['articleid'=>$post['articleid'],'isvip'=>"1"])->column('id,size');
			}

			foreach($chapter as $k=>$v){
				if(config('pricetype')==1){
					 Db::connect("database.db_config_two")->name('chapter')->where('id='.$k)->setField('chaptersaleprice',$post['price']);
				}else{
					 Db::connect("database.db_config_two")->name('chapter')->where('id='.$k)->setField('saleprice',round($v/1000*$post['price']));
				}
				//删除章节缓存
				\think\Cache::rm('chapterinfo'.$k);
			}
			return $this->success("设置成功！", url('admin/novel/index', array('model_id' => $this->modelInfo['id'])));
		}
		//获取默认章节售价配置信息
		$saleprice =  Db::connect("database.db_config_two")->name('config')->where(array('name'=>'chaptersaleprice'))->field("extra")->cache(true)->find();
		$chaptersaleprice = parse_field_attr($saleprice["extra"]);
		//获取默认千字售价配置信息
		$wordsperegold =  Db::connect("database.db_config_two")->name('config')->where(array('name'=>'wordsperegold'))->field("extra")->cache(true)->find();
		$wordsperegold = parse_field_attr($wordsperegold["extra"]);
		
		$this->assign('chaptersaleprice',$chaptersaleprice);
		$this->assign('wordsperegold',$wordsperegold);

		$this->assign('id',$id);
		$this->setMeta("批量设置价格");
		return $this->fetch();

	}

	/****设置章节数******/

	public function setchapters() {
		$novel =  Db::connect("database.db_config_two")->name('novel')->where('status=1')->column('id');

		foreach ($novel as $k=>$v){
			$chapters =  Db::connect("database.db_config_two")->name('chapter')->where(' articleid='.$v. ' and chaptertype=0')->count();
			 Db::connect("database.db_config_two")->name('novel')->where('id',$v)->update(['chapters' => $chapters]);
		}
	}

	//自定义章节售价
	public function diyprice() {
		if (IS_POST) {
			$data = input();
			$data['uid'] = session('user_auth.uid');
			$data['wxmpid'] = session('wxmpid');
			$diyprice =  Db::connect("database.db_config_two")->name('diyprice')->where("uid",$data['uid'])->where("wxmpid",session('wxmpid'))->where("articleid",$data['articleid'])->find();
			if($diyprice){
				$res =  Db::connect("database.db_config_two")->name('diyprice')->where("id",$diyprice["id"])->update(['wordsperegold' =>$data['wordsperegold'],'saleprice'=>$data['saleprice']]);
			}else{
				$data['create_time'] = time();
				$data['update_time'] = time();
				$res =  Db::connect("database.db_config_two")->name('diyprice')->insert($data);
			}

			if (false !== $res) {
				return $this->success("操作成功！");
			} else {
				return $this->error("操作失败！！");
			}
		}
	}
	
	//小说搜索记录
	public function searchlog() {
		
		$map = [];
		$keyword = input('keyword');
		if($keyword){
			$map['keyword'] = array("LIKE", "%$keyword%");
		}

		$list =  Db::connect("database.db_config_two")->name('search_info')->where($map)->order(' search_num desc')->paginate(25,false);
	
		$data = array(
			'list' => $list,
			'keyword' => $keyword,
			'page' => $list->render(),
		);
	
		$this->assign($data);
		$this->setMeta("小说搜索记录");
		return $this->fetch();
	}

	/**
	 * 获取字段信息
	 * @return array 字段数组
	 * @author netlife <40150501@qq.com>
	 */
	protected function getField() {
		$field_group = parse_config_attr($this->modelInfo['attribute_group']);

		$map['model_id'] = $this->modelInfo['id'];
		if ($this->request->action() == 'add') {
			$map['is_show'] = array('in', array('1', '2'));
		} elseif ($this->request->action() == 'edit') {
			$map['is_show'] = array('in', array('1', '3'));
		}

		//获得数组的第一条数组
		$rows    = model('Attribute')->getFieldlist($map, 'id');
		if (!empty($rows)) {
			foreach ($rows as $key => $value) {
				$list[$value['group_id']][] = $value;
			}
			foreach ($field_group as $key => $value) {
				$fields[$value] = isset($list[$key]) ? $list[$key] : array();
			}
		}else{
			$fields = array();
		}
		return $fields;
	}

	/**
	 * 创建搜索
	 * @return [array] [查询条件]
	 */
	protected function buildMap() {
		$map  = array();
		$data = $this->request->param();
		foreach ($data as $key => $value) {
			if ($value) {
				if ($key == 'keyword') {
					$map['title|author'] = array("LIKE", "%$value%");
				} elseif ($key == 'category') {
					$map['category_id'] = $value;
				} elseif ($key == 'create_time') {
					$map['create_time'] = array('BETWEEN', array(strtotime($value[0]), strtotime($value[1])));
				} elseif ($key == 'fullflag') {
					$map['fullflag'] = $value==1?1:0;
				} elseif ($key == 'is_new' || $key == 'allvisit' || $key == 'is_free' || $key == 'is_license' || $key == 'is_recommend' || $key == 'is_old' || $key == 'update' || $key == 'is_index' ||$key == 'chapters') {

				} else {
					$map[$key] = $value;
				}
			}
		}
		if (isset($map['page'])) {
			unset($map['page']);
		}
		
		if (isset($map['model_id'])) {
			unset($map['model_id']);
		}
		$this->assign($data);
		return $map;
	}

	protected function last_month_today($time){
		$last_month_time = mktime(date("G", $time), date("i", $time),
					date("s", $time), date("n", $time), 0, date("Y", $time));
		$last_month_t =  date("t", $last_month_time);

		if ($last_month_t < date("j", $time)) {
			return date("Y-m-t H:i:s", $last_month_time);
		}

		return date(date("Y-m", $last_month_time) . "-d", $time);
	}

	/**
	 * 检测需要动态判断的文档类目有关的权限
	 *
	 * @return boolean|null
	 *      返回true则表示当前访问有权限
	 *      返回false则表示当前访问无权限
	 *      返回null，则会进入checkRule根据节点授权判断权限
	 *
	 * @author 朱亚杰  <xcoolcc@gmail.com>
	 */
	protected function checkDynamic() {
		$model_id = $this->request->param('model_id');
		if (IS_ROOT) {
			return true; //管理员允许访问任何页面
		}
		$models = model('AuthGroup')->getAuthModels(session('user_auth.uid'));
		if (!$model_id) {
			return false;
		} elseif (in_array($model_id, $models)) {
			//返回null继续判断操作权限
			return null;
		} else {
			return false; //无权限
		}
		return false;
	}

	public function readList($file) {
		$list = array();
		$content = $this->read_txt($file);
		//$content =file_get_contents($file);

		//增加识别文本编码 2019.03.14
		$encode = mb_detect_encoding($content,array("ASCII",'UTF-8',"GB2312","GBK",'BIG5'));
		$content = $this->clearContent($content,$encode);

		$content = preg_replace('/\n(?:(?:VIP|最新|防采集|网友上传)\s*(?:卷|分卷|章节)|正文|作品相关)\s*/i', "\n", $content);
		//$content = $this->replacePlus($jieqiConfigs['article']['banwords'], '***', $content);
		
		
		if (preg_match_all('/\n.{0,20}(第(?:一|二|三|四|五|六|七|八|九|十|百|千|万|两|壹|廿|卅|卌|零|〇|１|２|３|４|５|６|７|８|９|０|①|⑴|㈠|[0-9])+(?:章|节|回).{0,50})\n/', $content, $match, PREG_OFFSET_CAPTURE) || preg_match_all('/\n((?:d|第|弟|递|滴|低|地|底|帝|的)*(?:一|二|三|四|五|六|七|八|九|十|百|千|万|两|壹|廿|卅|卌|零|〇|１|２|３|４|５|６|７|８|９|０|①|⑴|㈠|[0-9])+(?:部|卷|集|篇|册|章|节|回).{0,50})\n/', $content, $match, PREG_OFFSET_CAPTURE)) {
			if ($match[0][0][1] > 1000) {
				array_unshift($match[0], array('作品相关', -8));
				array_unshift($match[1], array('作品相关', -8));
			}
			$c = 0;
			foreach ($match[1] as $key => $val) {
				$start = $match[0][$key][1] + strlen($match[0][$key][0]);
				$end = isset($match[0][$key + 1]) ? $match[0][$key + 1][1] : strlen($content);
				$chapter = $this->splitword(substr($content, $start, $end - $start), $jieqiConfigs['article']['minwords'], $jieqiConfigs['article']['maxwords']);
				if (is_array($chapter)) {
					foreach ($chapter as $k => $v) {
						$list[$c] = array('name' => trim($val[0])." (".($k+1).")", 'size' => strlen($v), 'content' => "    ".str_replace("\n", "\r\n\r\n    ", $v));
						$c++;
					}
				} else {
					if (empty($chapter)) continue;
					$list[$c] = array('name' => trim($val[0]), 'size' => $end - $start, 'content' => "    ".str_replace("\n", "\r\n\r\n    ", $chapter));
					$c++;
				}
			}
		} else {
			$chapter = $this->splitword($content, 0, $jieqiConfigs['article']['splitwords']);
			if (!empty($chapter)) {
				$chapter = is_array($chapter) ? $chapter : array($chapter);
				foreach ($chapter as $key => $val) {
					$list[] = array('name' => "第 ".($key+1)." 章节", 'size' => strlen($val), 'content' => "    ".str_replace("\n", "\r\n\r\n    ", $val));
				}
			}
		}
		return $list;
	}
	

	protected function clearContent($string,$encode='') {
		if($encode !='UTF-8'){
			//$string = iconv('GBK', 'UTF-8//IGNORE', $string);
			$string = mb_convert_encoding($string, "UTF-8", $encode);
		}
		
		$string = str_replace("\t", ' ', $string);
		$string = str_replace("\r", "\n", $string);
		$string = $this->replacePlus('\\', '', $string);
		$string = $this->replacePlus('　', ' ', $string);
		$string = $this->replacePlus('；', ";\r", $string);
		while(stripos($string, '&amp;') !== false) {
			$string = str_ireplace('&amp;', '&', $string);
		}
		$string = str_ireplace(array('&#38;', '&amp', 'amp;'), '&', $string);
		$string = preg_replace(array('/&(apos|#39);/i', '/&(quot|#34);/i', '/&(nbsp|#160);/i', '/&(lt|#60);/i', '/&(gt|#62);/i'), array("'", '"', ' ', '<', '>'), $string);
		$string = html_entity_decode($string, ENT_QUOTES, 'GB2312');
		$string = str_ireplace(array('&apos', 'apos;', 'apos', '&quot', 'quot;', 'quot', '&nbsp', 'nbsp;', 'nbsp', '&lt', 'lt;', '&gt', 'gt;'), array("'", "'", "'", '"', '"', '"', ' ', ' ', ' ', '<', '<', '>', '>'), $string);
		$string = preg_replace('/&#?[a-zA-Z0-9]+;/', '', $string);
		$string = str_replace(";\r", '；', $string);
		$string = str_replace("\r", '', $string);
		$string = preg_replace('/<br[\s\/]*>/i', "\n", $string);
		$string = preg_replace('/<\/?p>/i', "\n", $string);
		$string = preg_replace('/<!--.*?-->|<\?|\?>|<%|%>|<@|@>/', '', $string);
		$string = preg_replace('/<(script|style).*\/\1>/is', '', $string);
		$string = preg_replace('/<\/?(?:html|head|meta|link|base|basefont|body|bgsound|title|style|script|noscript|object|form|select|option|iframe|frame|frameset|applet|button|code|event|id|input|ilayer|layer|name|xml|userprofile|table|tbody|thead|tfoot|th|tr|td|i|b|u|strong|img|p|br|div|em|ul|ol|li|dl|dd|dt|a|font|span|embed|hr|blockquote|h1|h2|h3|h4|h5|h6|sub|sup|strike)[^><]*>/i', '', $string);
		$string = strip_tags($string);
		while(strpos($string, '  ')) {
			$string = str_replace('  ', ' ', $string);
		}
		$line = explode("\n", trim($string));
		$string = '';
		foreach($line as $row) {
			$row = trim($row);
			if(strlen($row) > 1) $string .= "\n$row";
		}
		return rtrim($string);
		
	}

	protected function replacePlus($find, $replace, $string) {

		error_reporting(0);
		$find = is_array($find) ? $find : array($find);
		$replace = is_array($replace) ? array_unshift($replace, false) : array_pad(array(false), count($find) + 1, $replace);
		
		foreach ($find as $row) {
			$key = iconv('GBK', 'UTF-8//IGNORE', $row);
			$val = iconv('GBK', 'UTF-8//IGNORE', next($replace));
			if (strpos($string, $key) === false) continue;
			$string = str_replace($key, $val, $string);
		}
		return $string;		
	}

	protected function splitword($string, $minwords, $maxwords) {
		$wordnum = $this->strlenPlus($string);
		if ($minwords > 0 && $wordnum <= $minwords) return false;
		if ($maxwords <= 0 || $this->strlenPlus($string) <= $maxwords) return $string;
		preg_match_all('/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/', $string, $match);
		return array_map('implode', array_chunk($match[0], $maxwords));
	}

	protected function strlenPlus($string) {
		if(function_exists('iconv_strlen')) return iconv_strlen($string, 'UTF-8');
		if(function_exists('mb_strlen')) return mb_strlen($string, 'UTF-8');
		preg_match_all('/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/', $string, $match);
		return count($match[0]);
	}

	public function textstr($str, $unclickable = false)
	{
		$from = array('　', '＂');
		$to = array(' ', '"');
		$str = str_replace($from, $to, $str);
		return $str;
	}
	/*****对于上传的小说文本进行格式化******/
	public function format_content($string) {
		//$string = strip_tags($string);
		$string = '<p>'.str_replace(array("'","''",'"',"　"," ","\r\n", "\r", "\n","<br/>"), array("”","”","“",'','',"</p><p>","</p><p>","</p><p>",''), $string)."</p>"; 
		return $string;

	}

	public function getdata($siteid)
	{
		$map =[];
		if($siteid){
			$map['siteid']=$siteid;
		}else{
			$map['siteid']= -1;
		}
		$list =  Db::connect("database.db_config_two")->name('third_novel')->where($map)->order('id desc')->column('sourceid,title');
		echo json_encode(array("code"=>1,"data"=>$list));
	}
}